package com.chao.wind3j.base.config.redisConfig;

import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis 配置
 */
@Configuration
public class RedisConfig {

  @Bean(name = "redisTemplate")
  public RedisTemplate<String, Object> redisJackJsonTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> redisJackJsonTemplate = new RedisTemplate<>();
    redisJackJsonTemplate.setConnectionFactory(redisConnectionFactory);
    ParserConfig.getGlobalInstance().addAccept("com.chaochis.springboottestdemo");

    // 自定义的string序列化器和fastjson序列化器
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    // jackson 序列化器
    GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

    // kv 序列化
    redisJackJsonTemplate.setKeySerializer(stringRedisSerializer);
    redisJackJsonTemplate.setValueSerializer(jsonRedisSerializer);

    // hash 序列化
    redisJackJsonTemplate.setHashKeySerializer(stringRedisSerializer);
    redisJackJsonTemplate.setHashValueSerializer(jsonRedisSerializer);

    redisJackJsonTemplate.afterPropertiesSet();
    return redisJackJsonTemplate;
  }
}
